package com.vader.flea.service.impl;

import com.vader.flea.dao.ProductCategoryDao;
import com.vader.flea.dao.ProductDao;
import com.vader.flea.dto.ProductCategoryExecution;
import com.vader.flea.entity.ProductCategory;
import com.vader.flea.enums.ProductCategoryStateEnum;
import com.vader.flea.exceptions.ProductCategoryOperationException;
import com.vader.flea.service.ProductCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductCategoryServiceImpl implements ProductCategoryService {

    @Autowired
    private ProductDao productDao;

    @Autowired
    private ProductCategoryDao productCategoryDao;

    @Override
    public List<ProductCategory> getProductCategoryList(long shopId) {
        List<ProductCategory> productCategoryList = productCategoryDao.queryProductCategoryList(shopId);
        return productCategoryList;
    }

    @Override
    @Transactional
    public ProductCategoryExecution batchAddProductCategory(List<ProductCategory> productCategoryList) throws ProductCategoryOperationException {
        if (productCategoryList != null && productCategoryList.size() > 0) {
            try {
                int rows = productCategoryDao.batchInsertProductCategory(productCategoryList);
                if (rows <= 0) {
                    throw new ProductCategoryOperationException("店铺商品类别添加失败");
                } else {
                    return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
                }
            } catch (Exception e) {
                throw new ProductCategoryOperationException("batchAddProductCategory error" + e.getMessage());
            }
        } else {
            return new ProductCategoryExecution(ProductCategoryStateEnum.EMPTY_LIST);
        }
    }

    @Override
    @Transactional
    public ProductCategoryExecution deleteProductCategory(long productCategoryId, long shopId)
            throws ProductCategoryOperationException  {
        try{
            int rows = productDao.updateProductCategoryToNull(productCategoryId);
            if (rows<0){
                throw new ProductCategoryOperationException("商品类别更新失败");
            }
        }catch (Exception e){
            throw new ProductCategoryOperationException("deleteProductCategory error"+e.getMessage());
        }
        try {
             int rows = productCategoryDao.deleteProductCategory(productCategoryId,shopId);
             if (rows<=0){
                 throw new ProductCategoryOperationException("商品删除失败");
             }else {
                 return new ProductCategoryExecution(ProductCategoryStateEnum.SUCCESS);
             }
        }catch (Exception e){
            throw new ProductCategoryOperationException("deleteProductCategory error"+e.getMessage());
        }
    }
}


